﻿using System;
using System.Linq;
using System.Windows;

namespace Yuwell.AtomizerWeight.App.Views
{
    /// <summary>
    /// ArgsWindow.xaml 的交互逻辑
    /// </summary>
    public partial class VaporArgsWindow : Window
    {
        public VaporArgsWindow()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                CoreModule.Storages.MySqlDbStorage dbStorage = new CoreModule.Storages.MySqlDbStorage();

                var vaporInterval = Math.Abs(this.txtVaporInterval.Value) == 0 ? 1 : Math.Abs(this.txtVaporInterval.Value);
                var vaporLowValue = Math.Abs(this.txtVaporLowValue.Value);
                var vaporHighValue = Math.Abs(this.txtVaporHighValue.Value);

                dbStorage.MeasurementArgs
                    .Add(new CoreModule.MeasurementArg()
                {
                    VaporInterval =(int) vaporInterval,
                    VaporLowValue = Math.Min(vaporLowValue, vaporHighValue),
                    VaporHighValue = Math.Max(vaporLowValue, vaporHighValue),
                    ClientId = CoreModule.Extension.GetClientId(),
                }); ;
                dbStorage.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {

                CoreModule.Storages.MySqlDbStorage dbStorage = new CoreModule.Storages.MySqlDbStorage();

                var arg = dbStorage.MeasurementArgs
                      .Where(item => item.ClientId == CoreModule.Extension.GetClientId())
                     .OrderByDescending(item => item.RefTime)
                     .FirstOrDefault();

                if (arg != null)
                {
                    this.txtVaporInterval.Value = arg.VaporInterval;
                    this.txtVaporLowValue.Value = arg.VaporLowValue;
                    this.txtVaporHighValue.Value = arg.VaporHighValue;
                }
                else
                {
                    this.txtVaporInterval.Value = 1;
                    this.txtVaporLowValue.Value = 0;
                    this.txtVaporHighValue.Value = 1;
                }
            }
            catch (Exception x)
            {

            }
        }
    }
}
